package com.xiumu.service.blog.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiumu.common.core.exception.blog.BlogException;
import com.xiumu.common.core.utils.AssertUtil;
import com.xiumu.dao.blog.BlogTagDao;
import com.xiumu.pojo.blog.entity.BlogTag;
import com.xiumu.pojo.blog.query.BlogTagQuery;
import com.xiumu.service.blog.BlogTagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章标签 Service 接口实现
 *
 * @author XiuMu
 * @Date 2023-01-30 14:21:26
 */
@Service
public class BlogTagServiceImpl extends ServiceImpl<BlogTagDao, BlogTag> implements BlogTagService {

    @Override
    public List<String> listLikeTagName(String tagName, boolean all) {
        List<BlogTag> blogTagList = new ArrayList<>();
        if (all){
            blogTagList.addAll(list(Wrappers.lambdaQuery(BlogTag.class).like(StrUtil.isNotBlank(tagName), BlogTag::getTagName, tagName)));
        }else {
            Page<BlogTag> page = this.page(new Page<BlogTag>(1, 20, false), Wrappers.lambdaQuery(BlogTag.class).like( StrUtil.isNotBlank(tagName), BlogTag::getTagName, tagName));
            blogTagList.addAll(page.getRecords());
        }
        return blogTagList.stream().map(BlogTag::getTagName).toList();
    }

    @Override
    public List<String> listFrequentTagName() {
        return this.baseMapper.listFrequentTagName();
    }

    @Override
    public List<String> listByBlogTagQuery(BlogTagQuery query) {
        if (query.isFrequent()){
            // 后续可以改成从 redis 里获取
            return listFrequentTagName();
        }
        return listLikeTagName(query.getTagName(), query.isAll());
    }

    @Override
    @Transactional
    public boolean create(String tagName) {
        AssertUtil.isTrue(StrUtil.isNotBlank(tagName), BlogException.EMPTY_TAG_NAME);
        BlogTag tag = getOne(Wrappers.lambdaQuery(BlogTag.class).eq(BlogTag::getTagName, tagName));
        if (tag == null) {
            // 标签不存在才创建
            return this.save(new BlogTag(tagName));
        }
        return true;
    }
}




